Imports KanBan.Pgd.Common
Imports KanBan.Pgd.Domain
Imports System.Text
Imports System.Data.SqlClient

Public Class IntegrityHelper(Of T As ISecurableEntity)

    Public Shared Function GetCalculatedCheckSum(ByVal entity As T) As String

        If entity Is Nothing Then
            Throw New ArgumentNullException("entity")
        End If

        Dim input As String = entity.GetSecurableProperties()

        Return Encryption.EncryptMD5(input)

    End Function

    Public Shared Function IsCheckSumValid(ByVal entity As T) As Boolean

        If entity Is Nothing Then
            Throw New ArgumentNullException("entity")
        End If

        Dim savedChechSum As String = entity.CheckSum
        Dim calculatedCheckSum As String = Encryption.EncryptMD5(entity.GetSecurableProperties())

        Return savedChechSum = calculatedCheckSum

    End Function

    Public Shared Function GetCalculatedMasterCheckSum(ByVal entity As T) As String

        Dim conn As New SqlConnection(PgdSettings.ConnectionString)
        Dim cmd As New SqlCommand(entity.MasterCheckSumStoredProcedure, conn)
        cmd.CommandType = CommandType.StoredProcedure

        Dim da As New SqlDataAdapter()
        da.SelectCommand = cmd

        Dim checkSums As New DataSet()

        conn.Open()
        da.Fill(checkSums)
        conn.Close()

        Dim builder As New StringBuilder()

        For Each r As DataRow In checkSums.Tables(0).Rows
            builder.Append(r.Item("CheckSum").ToString())
        Next

        Return Encryption.EncryptMD5(builder.ToString())

    End Function

    Public Shared Sub UpdateMasterCheckuSum(ByVal entity As T)

        Dim checkSum As String = GetCalculatedMasterCheckSum(entity)

        Dim conn As New SqlConnection(PgdSettings.ConnectionString)
        Dim cmd As New SqlCommand("UpdateMasterCheckSum", conn)
        cmd.CommandType = CommandType.StoredProcedure

        cmd.Parameters.AddWithValue("@masterCheckSumId", entity.MasterCheckSumId)
        cmd.Parameters.AddWithValue("@checkSum", checkSum)

        conn.Open()
        cmd.ExecuteNonQuery()
        conn.Close()

    End Sub

    Public Shared Function GetStoredMasterCheckSum(ByVal entity As T) As String

        Dim conn As New SqlConnection(PgdSettings.ConnectionString)
        Dim cmd As New SqlCommand("GetMasterCheckSum", conn)
        cmd.CommandType = CommandType.StoredProcedure

        cmd.Parameters.AddWithValue("@masterCheckSumId", entity.MasterCheckSumId)

        Dim da As New SqlDataAdapter()
        da.SelectCommand = cmd

        Dim checkSum As New DataSet()

        conn.Open()
        da.Fill(checkSum)
        conn.Close()

        Return checkSum.Tables(0).Rows(0).Item("CheckSum").ToString()

    End Function

End Class
